<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class YhGoods extends Model
{
    use SoftDeletes;

    protected $table = 'ims_yh_goods';
    
    protected $fillable = [
        'uniacid', 'store_id', 'brand_id', 'type', 'status', 'display_order',
        'title', 'alias', 'sku', 'thumb', 'thumb_url', 'video_url', 'detail_url',
        'category_id_1', 'category_id_2',
        'market_price', 'price', 'cost_price', 'stock', 'reduce_stock_method',
        'has_option', 'option_count',
        'weight', 'volume',
        'goods_sn', 'product_sn',
        'description', 'content',
        'is_new', 'is_hot', 'is_discount', 'is_recommand', 'is_comment',
        'show_sales', 'real_sales', 'virtual_sales', 'comment_num',
        'min_buy', 'max_buy', 'is_limit', 'need_address', 'no_refund',
        'is_deleted', 'is_plugin', 'plugin_id', 'vendor_id'
    ];

    protected $casts = [
        'thumb_url' => 'json',
        'detail_url' => 'json',
        'market_price' => 'decimal:2',
        'price' => 'decimal:2',
        'cost_price' => 'decimal:2',
        'weight' => 'decimal:2',
        'volume' => 'decimal:3',
        'is_new' => 'boolean',
        'is_hot' => 'boolean',
        'is_discount' => 'boolean',
        'is_recommand' => 'boolean',
        'is_comment' => 'boolean',
        'is_limit' => 'boolean',
        'is_deleted' => 'boolean',
    ];

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';
    const DELETED_AT = 'deleted_at';

    // 禁用时间戳自动转换为Carbon对象，因为表中使用整型存储
    public $timestamps = true;
    protected $dateFormat = 'U'; // 使用Unix时间戳

    /**
     * 关联商品规格
     */
    public function specs()
    {
        return $this->hasMany(HhmGoodsSpec::class, 'goods_id', 'id');
    }

    /**
     * 关联商品SKU选项
     */
    public function options()
    {
        return $this->hasMany(HhmGoodsOption::class, 'goods_id', 'id')
            ->where('is_enabled', 1);
    }

    /**
     * 关联商品分类（多对多）
     */
    public function categories()
    {
        return $this->belongsToMany(
            HhmCategory::class,
            'ims_hhm_goods_category',
            'goods_id',
            'category_id'
        );
    }

    /**
     * 关联一级分类
     */
    public function firstCategory()
    {
        return $this->belongsTo(HhmCategory::class, 'category_id_1', 'id');
    }

    /**
     * 关联二级分类
     */
    public function secondCategory()
    {
        return $this->belongsTo(HhmCategory::class, 'category_id_2', 'id');
    }

    /**
     * 作用域：只查询上架商品
     */
    public function scopeOnSale($query)
    {
        return $query->where('status', 1);
    }

    /**
     * 作用域：只查询未删除的商品
     */
    public function scopeNotDeleted($query)
    {
        return $query->where('is_deleted', 0);
    }

    /**
     * 获取实际显示销量
     */
    public function getTotalSalesAttribute()
    {
        return ($this->show_sales ?? 0) + ($this->real_sales ?? 0) + ($this->virtual_sales ?? 0);
    }

    /**
     * 获取商品主图完整URL
     */
    public function getThumbUrlAttribute($value)
    {
        if (empty($this->attributes['thumb'])) {
            return '';
        }
        return \App\Services\ImageUrlService::processImageUrl($this->attributes['thumb']);
    }
}

